<template>
  <div class="app-container">
    <!--查询-->
    <el-form :inline="true" :model="trainQuery" class="demo-form-inline">
      <el-form-item label="名字">
        <el-select v-model="trainQuery.userId" filterable clearable placeholder="输入名字">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="trainQuery.status" style="margin-left: 10px;width: 80%" clearable placeholder="可搜索">
          <el-option
            v-for="status in statusEnum"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="handleAddTrain">创建培训计划</el-button>

    <el-table :data="trainList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="名字">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="trainDate" label="培训日期">
        <template slot-scope="scope">
          <el-date-picker readonly v-model="scope.row.trainDate" type="datetime" placeholder="培训日期"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="content" label="培训内容">
        <template slot-scope="scope">
          {{ scope.row.content }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="remark" label="备注">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" style="margin-left: 10px;width: 80%" placeholder="状态"
                     @change="changeStatus(scope)">
            <el-option
              v-for="status in statusEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getTrains"
      />
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit train':'New train'">
      <el-form :model="train" label-width="80px" label-position="left">
        <el-form-item label="培训人员" v-if="dialogType==='new'">
          <el-select v-model="userIds" filterable multiple placeholder="输入名字">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="培训日期">
          <el-date-picker
            v-model="train.trainDate"
            type="datetime"
            value-format="timestamp"
            placeholder="时间点">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考评内容">
          <el-input v-model="train.content" placeholder="内容"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="train.remark" placeholder="备注"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmTrain">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { batchAddTrain, getTrains, modifyTrain, modifyStatus} from '@/api/train'
import { deepClone } from '@/utils'
import { getUserList } from '@/api/user'

const defaultTrain = {
  id: ''
}

export default {
  name: 'TrainManager',
  components: {},
  data() {
    return {
      train: Object.assign({}, defaultTrain),
      trainList: [],
      userList: [],
      userIds: [],
      trainQuery: {},
      statusEnum: [
        {value: 'BEGINNING', label: "正在进行"},
        {value: 'END', label: "结束"},
        {value: 'NOT_BEGIN', label: "未开始"},
        {value: 'FALSE', label: "无效"},
      ],
      checkStrictly: false,
      total: 100,
      page: 1,
      limit: 20,
      dialogType: 'new',
      dialogVisible: false,
    };
  },
  //方法集合
  methods: {
    async getTrains(page = 1){
      const offset = this.limit * (page - 1);
      const res = await getTrains(this.trainQuery, offset, this.limit)
      this.trainList = res.data.rows
      this.total = res.data.total
    },
    onSubmit() {
      this.getTrains()
    },
    async getUserList() {
      const res = await getUserList()
      this.userList = res.data
    },
    handleAddTrain() {
      this.userIds = []
      this.train = Object.assign({}, defaultTrain)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.train = deepClone(scope.row)
      this.$nextTick(() => {
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
      })
    },
    async confirmTrain() {
      if ('edit' === this.dialogType) {
        await modifyTrain(this.train.id, this.train)
        for (let index = 0; index < this.trainList.length; index++) {
          if (this.trainList[index].id === this.train.id) {
            this.trainList.splice(index, 1, Object.assign({}, this.train))
            break
          }
        }
      } else {
        const length = this.userIds.length
        this.train.userIds = this.userIds.slice(0, length)
        await batchAddTrain(this.train)
      }
      this.dialogVisible = false
      await this.getTrains()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '操作成功',
        type: 'success'
      })
    },
    changeStatus({ $index, row }){
      this.$confirm('确定要修改计划状态吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await modifyStatus(row.id, row.status)
          // this.userList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '修改状态成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getTrains()
    this.getUserList()
  }
}

</script>

<style scoped>
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
